package cn.yzstu.core;

import cn.yzstu.support.Constants;
import cn.yzstu.support.DateUtil;
import cn.yzstu.support.FileUtil;
import cn.yzstu.support.SystemUtil;

public class LogUtil {

    //日志写入操作
    public static void write2file(String path, String fileName, String content) {

        //获取当前日期，我们的日志保存的文件夹名是自定义path+日期
        String date = DateUtil.getDate()+"/";

        try {
            //传了path，那我们直接用这个path
            if (null != path && 0 != path.length()) {
                //写入
                FileUtil.write(path + date + fileName + ".txt",
                        DateUtil.getDateTime() + ":" + content + "\r\n");
            } else {
                //没有传path或错误使用默认的路径
                if (SystemUtil.isLinux()) {
                    FileUtil.write(Constants.LINUX_LOG_PATH + date + fileName + ".txt",
                            DateUtil.getDateTime() + ":" + content + "\r\n");
                } else {
                    FileUtil.write(Constants.WIN_LOG_PATH + date + fileName + ".txt",
                            DateUtil.getDateTime() + ":" + content + "\r\n");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

/*    public static void checkDirectory(String path) {
        File file = new File(path);
        //如果文件夹不存在则创建
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
    }*/

    // 在已经存在的文件后面追加写的方式
   /* private static boolean write(String path, String str) throws Exception {
        File f = new File(path);
        File fileParent = f.getParentFile();

        BufferedWriter bw = null;
        try {
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }

            if (!f.exists()) {
                f.createNewFile();
            }
            // new FileWriter(name,true)设置文件为在尾部添加模式,参数为false和没有参数都代表覆写方式
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, true), StandardCharsets.UTF_8));
            bw.write(str);
        } catch (Exception e) {
            System.out.println("arg1:" + path);
            System.out.println("arg2:" + str);
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (bw != null) bw.close();
            } catch (Exception e) {
                throw new Exception("FileUtil.write colse bw wrong:" + e);
            }
        }
        return true;
    }*/
}
